package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.Settings;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exceptions.BusinessException;
import com.tanhua.server.intercepror.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    /**
     * 根据id查询用户信息
     *
     * @param userID
     * @return
     */
    public UserInfoVo findUserInfoId(Long userID) {
        //查询数据库中的UserInfo对象
        UserInfo info = userInfoApi.findById(userID);
        //将UserInfo对象转化成UserInfoVo
        UserInfoVo vo = new UserInfoVo();
        //将参数一对象中的同名+同类型属性开拷贝到参数二中
        BeanUtils.copyProperties(info, vo);
        if (info.getAge() != null) {
            vo.setAge(info.getAge().toString());
        }
        return vo;
    }

    /**
     * 更新用户信息
     *
     * @param userInfo
     */
    public void updataUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 查询通用设置
     *
     * @return
     */
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //设置id和手机号
        vo.setId(UserHolder.getUserId());
        vo.setPhone(UserHolder.getMobile());
        //查询并设置陌生人问题
        //根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(UserHolder.getUserId());
        vo.setStrangerQuestion(question == null ? "你喜欢JAVA吗？" : question.getTxt());
        //查询并设置通知开关
        //根据用户id查询通知开关
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if (settings != null) {
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
        }
        return vo;
    }

    /**
     * 设置陌生人消息
     *
     * @param content
     */
    public void questions(String content) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.调用api根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        //3.判断对象是否存在
        if (question != null) {
            //存在进行更新
            question.setTxt(content);
            questionApi.update(question);
        } else {
            //不存在进行保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }
    }

    /**
     * 设置通知开关：保存或更新
     */
    public void setting(Boolean likeNotifi, Boolean pinglunNotifi, Boolean gonggaoNotifi) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.调用API根据用户id查询通知开关
        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            //3.如果对象存在，调用API更新
            settings.setLikeNotification(likeNotifi);
            settings.setPinglunNotification(pinglunNotifi);
            settings.setGonggaoNotification(gonggaoNotifi);
            settingsApi.update(settings);
        } else {
            //4.如果不存在，调用API保存
            settings = new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotifi);
            settings.setPinglunNotification(pinglunNotifi);
            settings.setGonggaoNotification(gonggaoNotifi);
            settingsApi.save(settings);
        }
    }

    /**
     * 分页查询黑名单数据
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult blacklist(Integer page, Integer pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用API分页查询黑名单数据。IPage对象
        IPage<UserInfo> iPage = blackListApi.findByUserId(userId, page, pagesize);
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 移除黑名单---删除黑名单中的数据
     *
     * @param blackUserId
     */
    public void blackUserId(Long blackUserId) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用API删除黑名单中的数据
        blackListApi.delate(userId, blackUserId);
    }

    /**
     * @param page
     * @param type 、
     *             查询类型
     *             * 1 互相关注
     *             * 2 我关注
     *             * 3 粉丝
     *             * 4 谁看过我 （今天内容）
     * @return
     */
    public PageResult friends(Integer type, Integer page, Integer pagesize) {
        if (type != 4) {
            return new PageResult();
        }
        //1.根据用户id查询访客数据
        Long userId = UserHolder.getUserId();
        List<Visitors> list = visitorsApi.findAll(userId, page, pagesize);
        //判断，没数据返回一个空的vo
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取所有访客的信息
        List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        List<UserLikeListVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            Long id = visitors.getVisitorUserId();
            UserInfo userInfo = map.get(id);
            UserLikeListVo vo = UserLikeListVo.init(userInfo, visitors);
            vos.add(vo);
        }
        //设置查询历史访客时间
        String key = Constants.VISITORS_USER + userId;
        Long value = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, value.toString());
        //构造返回
        return new PageResult(page, pagesize, 0l, vos);
    }

    //改手机号- 1 发送短信验证码
    public void sendVerificationCode() {
        //获取手机号
        String mobile = UserHolder.getMobile();//手机号
        String code = "123456";//验证码
        //发送短信 不发了
        //直接将存入redis
        redisTemplate.opsForValue().set("CODE" + mobile, code, 5, TimeUnit.MINUTES);//5分钟后失效

    }

    //修改手机号 - 2 校验验证码
    public Boolean checkVerificationCode(String code) {
        String mobile = UserHolder.getMobile();
        //1。判断验证码
        //从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("CODE" + mobile);
        //比较
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //不一致报错
            return false;
        }
        redisTemplate.delete("CODE" + mobile);
        return true;
    }

    //修改手机号 - 3 保存
    public void phone(String phone) {
        User user = UserHolder.getUser();

        user.setMobile(phone);
        userApi.update(user);
    }

}
